//
//  OnlinePicAndVideoViewController.m
//  marrymarry
//
//  Created by lsj on 16/10/9.
//  Copyright © 2016年 cf. All rights reserved.
//
static NSString * clickCellID = @"ClickTableViewCell";
static NSString * groundCellID = @"groundTableViewCell";
#import "OnlinePicAndVideoViewController.h"
#import "ClickTableViewCell.h"
#import "groundTableViewCell.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
@interface OnlinePicAndVideoViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIWebViewDelegate>
{
    NSString * _lookWhat;
    NSString * _top_img_homeStr;
    NSString * _top_firstimg_homeStr;
    NSString * _top_secimg_homeStr;
    NSString * _top_thridimg_homeStr;
    
    NSString * _headimgPath;
    NSString * _secondImgPath;
    NSString * _thirdImgPath;
    
    
    UIImage * _FirstImg;
    UIImage * _SecondImg;
    UIImage * _ThirdImg;
    
    NSDictionary * _firstDic;
    NSDictionary * _secondDic;
    NSDictionary * _thirdDic;
    
    NSMutableArray * _imgArry;
    NSMutableArray * _myNetPicArry;
    NSArray * _myPicUrlArry;
    
    int myImgTag;
    BOOL isreloadIMG;
    BOOL netHavePhoto;
    int statusWithCheck;
     BOOL isOnlineVideo;
    NSURL * _videoStrUrl;
    NSMutableArray * myVideoUrlArry;
@private
    NSURL *_videoURL;
    NSString *_fileName;
    
    
}
///标题
@property (weak, nonatomic) IBOutlet UILabel *MyTitleLabel;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (nonatomic,strong) NSMutableArray * MyPicStrArry;
@property (strong,nonatomic) UIImageView * imgView;
@property (strong , nonatomic) NSArray * selectPicArry;
@property (nonatomic, strong) NSArray<ZLSelectPhotoModel *> *lastSelectMoldels;
@property (nonatomic, strong) NSArray *arrDataSources;
@property (strong,nonatomic) UIScrollView * imgScrollView;
@property (strong,nonatomic) NSMutableDictionary * myBigDic;
@property (nonatomic,strong) MPMoviePlayerController *moviePlayer;//视频播放控制器
@end

@implementation OnlinePicAndVideoViewController
-(NSMutableDictionary *)myBigDic
{
    if (!_myBigDic) {
        _myBigDic = [NSMutableDictionary new];
        
    }
    return _myBigDic;
}
-(NSMutableArray *)MyPicStrArry
{
    if (!_MyPicStrArry) {
        _MyPicStrArry = [NSMutableArray new];
        
    }
    return  _MyPicStrArry;
}
///选择存储img的数组
-(NSArray *)selectPicArry
{
    if (!_selectPicArry) {
        _selectPicArry = [NSArray new];
    }
    return _selectPicArry;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _imgArry = [NSMutableArray new];
    _myPicUrlArry = [NSMutableArray new];
    
    if (self.isVideoType) {
        self.MyTitleLabel.text = @"拍摄认证视频";
         _lookWhat = @"video";
        myVideoUrlArry = [NSMutableArray new];
    }else{
    self.MyTitleLabel.text = @"拍摄在线照片";
        _lookWhat = @"image";
    }
    
    
  
    statusWithCheck =10;
    isreloadIMG = YES;
    if (self.isOtherWatch) {
        self.saveBtn.hidden= YES;
        NSLog(@"%@",self.otherID);
        [self requestTheNetWith:nil andURL:WATCHONLINE_URL andDic:@{@"id":self.otherID,@"type":_lookWhat} andRequestSingStr:_lookWhat];
    }else
    {
        self.saveBtn.hidden = NO;
        [self requestTheNetWith:nil andURL:WATCHONLINE_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID],@"type":_lookWhat} andRequestSingStr:_lookWhat];
        
    }
    
    
    
}


#pragma mark UITableViewDatasource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    
    
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   groundTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:groundCellID];
    if (!cell) {
        cell = [[groundTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:groundCellID];
    }
    
    if (isreloadIMG) {
        //            NSDictionary * dic = [NSDictionary new];
        for (UIImageView * myOldImgView in cell.myScrollView.subviews ) {
            [myOldImgView removeFromSuperview];
        }
        if (self.isVideoType) {
            for (int i = 0; i<self.MyPicStrArry.count; i++) {
                if (statusWithCheck == 0 || self.isOtherWatch) {
                    NSLog(@"%@",self.MyPicStrArry[i]);
//cell.moviePlayer=[[MPMoviePlayerController alloc]initWithContentURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.MyPicStrArry[i]]]];
//                    cell.moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
//                    cell.moviePlayer.shouldAutoplay = NO;
//                    cell.moviePlayer.view.frame =CGRectMake(8,30,ScreenWidth-16,160);
//                    self.myTableView.scrollEnabled = NO;
                UIWebView *myWeb = [[UIWebView alloc] initWithFrame:CGRectMake(8,30,ScreenWidth-16,160)];
               NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.MyPicStrArry[i]]]];
                        [myWeb setDelegate:self];
                        [myWeb loadRequest:request];
                        [cell addSubview:myWeb];
                    
                }else{}
                /** 如果status为1 对界面处理 **/
                if (statusWithCheck == 0 ||self.isOtherWatch) {
              
                }else
                {}
            }
            cell.myScrollView.contentSize = CGSizeMake(self.MyPicStrArry.count * (140+2), 0);
            //        cell.picNumLabel.text =[NSString stringWithFormat:@"照片(%d)",(int)self.MyPicStrArry.count];
            cell.myScrollView.tag =200;
            cell.selectionStyle = UITableViewCellAccessoryNone;
            cell.addPhotoImgView.userInteractionEnabled =YES;
            if (self.isVideoType) {
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addVideo)];
                [cell.addPhotoImgView addGestureRecognizer:tap];
            }else{
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addphoto)];
                [cell.addPhotoImgView addGestureRecognizer:tap];
            }
        
        cell.backgroundColor = RGB(245, 245, 247);
        isreloadIMG = NO;
    
        }else{
       
            for (int i = 0; i<self.MyPicStrArry.count; i++) {
                cell.imgView = [UIImageView new];
                cell.imgView.frame = CGRectMake(0+140*i+2*i,0,140,140);
                if (statusWithCheck == 0 || self.isOtherWatch) {
                    [cell.imgView setImageWithURL:[NSURL URLWithString:self.MyPicStrArry[i]]];
                }else{
                cell.imgView.image = self.selectPicArry[i];
                }
                cell.imgView.tag = i;
                 /** 如果status为1 对界面处理 **/
                if (statusWithCheck == 0 ||self.isOtherWatch) {
                    [cell.myBigScrollView addSubview:cell.imgView];
                    }else
                    {
                        [ cell.myScrollView addSubview:cell.imgView];
                    }
                
                cell.imgView.userInteractionEnabled = YES;
                cell.imgView.contentMode = UIViewContentModeScaleToFill;
                cell.imgView.clipsToBounds = YES;
                CFUITapGestureRecognizer * imgbigTap = [[CFUITapGestureRecognizer alloc]initWithTarget:self action:@selector(imgbig:)];
                imgbigTap.tapImgView = cell.imgView;
                [cell.imgView addGestureRecognizer:imgbigTap];
            }
        }
        /** 如果status为1 对界面处理 **/
        if (statusWithCheck == 0||self.isOtherWatch) {
            cell.myBigScrollView.hidden =NO;
            cell.myScrollView.hidden = YES;
            cell.addPhotoImgView.hidden = YES;
            cell.myBigScrollView.contentSize = CGSizeMake(self.MyPicStrArry.count * (140+2), 0);
            cell.myBigScrollView.tag =200;
            cell.selectionStyle = UITableViewCellAccessoryNone;
          
        }else{
        cell.myScrollView.contentSize = CGSizeMake(self.MyPicStrArry.count * (140+2), 0);
//        cell.picNumLabel.text =[NSString stringWithFormat:@"照片(%d)",(int)self.MyPicStrArry.count];
        cell.myScrollView.tag =200;
        cell.selectionStyle = UITableViewCellAccessoryNone;
        cell.addPhotoImgView.userInteractionEnabled =YES;
            if (self.isVideoType) {
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addVideo)];
                [cell.addPhotoImgView addGestureRecognizer:tap];
            }else{
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addphoto)];
        [cell.addPhotoImgView addGestureRecognizer:tap];
            }
        }
        cell.backgroundColor = RGB(245, 245, 247);
        isreloadIMG = NO;
    }
    
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   
}


#pragma mark -------返回上一级
- (IBAction)gobackVC:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -------点击了保存
- (IBAction)saveBtnClicked:(UIButton *)sender {
    if (self.isVideoType&& _videoURL != nil) {
        NSURL * URL = _videoURL;
    
            CGFloat size = [self getFileSize:[URL path]];
            NSString *message;
            NSString *sizeString;
            CGFloat sizemb= size/1024;
            if(size<=1024) {
                sizeString = [NSString stringWithFormat:@"%.2fKB",size];
            }else{
                sizeString = [NSString stringWithFormat:@"%.2fMB",sizemb];
            }
        
            if(sizemb<2) {
                [self uploadVideo:URL];
            }
        
            else if(sizemb<=5) {
                message = [NSString stringWithFormat:@"视频%@，大于2MB会有点慢，确定上传吗？", sizeString];
                UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                                          message: message
                                                                                   preferredStyle:UIAlertControllerStyleAlert];
        
                [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
                    [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间（沙盒）
        
                }]];
                [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        
                    [self uploadVideo:URL];
        
                }]];
                [self presentViewController:alertController animated:YES completion:nil];
        
            }else if(sizemb>5) {
                message = [NSString stringWithFormat:@"视频%@，超过5MB，不能上传，抱歉。", sizeString];
                UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                                          message: message
                                                                                   preferredStyle:UIAlertControllerStyleAlert];
        
                [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
                    [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间
                    
                }]];
                [self presentViewController:alertController animated:YES completion:nil];
            }

        
        
    }else{
    if (self.selectPicArry.count>0) {
        

    for (int i = 0; i< self.MyPicStrArry.count;i++) {
        NSDictionary * dic = @{@"imgname":@"onlineimage",@"pic":self.MyPicStrArry[i]};
        [_imgArry addObject:dic];
    }
    [self requestTheNetWith:_imgArry andURL:ONLINEPIC_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID]} andRequestSingStr:@"image"];
    }
    }
}

-(void)addphoto
{
    
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置照片最大选择数
    actionSheet.maxSelectCount = 5;
    //设置照片最大预览数
    actionSheet.maxPreviewCount = 0;
    actionSheet.photolibraryBtn.hidden = YES;
    weakify(self);
    [actionSheet showWithSender:self animate:YES lastSelectPhotoModels:self.lastSelectMoldels completion:^(NSArray<UIImage *> * _Nonnull selectPhotos, NSArray<ZLSelectPhotoModel *> * _Nonnull selectPhotoModels) {
        strongify(weakSelf);
        strongSelf.arrDataSources = selectPhotos;
        strongSelf.lastSelectMoldels = selectPhotoModels;
        NSLog(@"%@", selectPhotos);
        self.selectPicArry = strongSelf.arrDataSources;
        self.MyPicStrArry = [NSMutableArray arrayWithArray:self.selectPicArry];
        [self.myTableView reloadData];
        isreloadIMG= YES;
        
        
    }];
    
    
}

-(void)addVideo
{
     [self recordVideoWithCamera];
}

//用相机拍摄视频
- (void)recordVideoWithCamera {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    imagePicker.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
    [self presentViewController:imagePicker animated:YES completion:nil];
    imagePicker.videoMaximumDuration = 30.0f;//30秒
    imagePicker.delegate = self;//设置委托
}

//创建视屏播放器
- (void)initMoviePlayer {
    NSLog(@"222");
    NSURL *url = _videoURL;
    _moviePlayer=[[MPMoviePlayerController alloc]initWithContentURL:url];
    _moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
    _moviePlayer.shouldAutoplay = NO;
    CGFloat width = [[UIScreen mainScreen] bounds].size.width;
    _moviePlayer.view.frame =CGRectMake(8,64+30,ScreenWidth,160);
    [self.view addSubview:_moviePlayer.view];
    self.myTableView.scrollEnabled = NO;
   
    
}
/**
 *  添加通知监控媒体播放控制器状态
 */
-(void)addNotification {
    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerThumbnailRequestFinished:) name:MPMoviePlayerThumbnailImageRequestDidFinishNotification object:self.moviePlayer];
}



#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
    //    NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
    //    NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[sourceURL path]]]);
    NSURL *newVideoUrl; //一般.mp4
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    _fileName = [formater stringFromDate:[NSDate date]];
    newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@.mp4", _fileName]];//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉。我建议删除掉，免得占空间。
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void) convertVideoQuailtyWithInputURL:(NSURL*)inputURL
                               outputURL:(NSURL*)outputURL
                         completeHandler:(void (^)(AVAssetExportSession*))handler
{
    
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
    
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.shouldOptimizeForNetworkUse= YES;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
         switch (exportSession.status) {
             case AVAssetExportSessionStatusCancelled:
                 NSLog(@"AVAssetExportSessionStatusCancelled");
                 break;
             case AVAssetExportSessionStatusUnknown:
                 NSLog(@"AVAssetExportSessionStatusUnknown");
                 break;
             case AVAssetExportSessionStatusWaiting:
                 NSLog(@"AVAssetExportSessionStatusWaiting");
                 break;
             case AVAssetExportSessionStatusExporting:
                 NSLog(@"AVAssetExportSessionStatusExporting");
                 break;
             case AVAssetExportSessionStatusCompleted:
                 //                 NSLog(@"AVAssetExportSessionStatusCompleted");
                 //                 NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
                 //                 NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);
                 
                 //UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册
                 [self alertUploadVideo:outputURL];
                 
                 break;
             case AVAssetExportSessionStatusFailed:
                 NSLog(@"AVAssetExportSessionStatusFailed");
                 break;
         }
     }];
}

-(void)alertUploadVideo:(NSURL*)URL {
    if (![[NSThread currentThread] isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"333");
            _videoURL = [URL copy];
            [self initMoviePlayer];
            [self addNotification];
            [self thumbnailImageRequest];
        });
    }
 
    
}

-(void)uploadVideo:(NSURL*)URL {
    isOnlineVideo = YES;
    _videoStrUrl = URL;
    NSData *data = [NSData dataWithContentsOfURL:URL];
    [self requestTheNetWith:@[data] andURL:ONLINEVIDEO_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID],@"sessionkey":[Tools getValueFromNSUserDefaultsByKey:USERSESSION]} andRequestSingStr:@"video"];
    
}


//此方法可以获取文件的大小，返回的是单位是KB。
- (CGFloat) getFileSize:(NSString *)path
{
    NSLog(@"%@",path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }else{
        NSLog(@"找不到文件");
    }
    return filesize;
}

//此方法可以获取视频文件的时长。
- (CGFloat) getVideoLength:(NSURL *)URL
{
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
    CMTime time = [avUrl duration];
    int second = ceil(time.value/time.timescale);
    return second;
}

/**
 *  播放状态改变，注意播放完成时的状态是暂停
 *
 *  @param notification 通知对象
 */
-(void)mediaPlayerPlaybackStateChange:(NSNotification *)notification {
    switch (self.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"正在播放...");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放.");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放.");
            break;
        default:
            NSLog(@"播放状态:%li",self.moviePlayer.playbackState);
            break;
    }
}

/**
 *  播放完成
 *
 *  @param notification 通知对象
 */
-(void)mediaPlayerPlaybackFinished:(NSNotification *)notification {
    NSLog(@"播放完成.%li",self.moviePlayer.playbackState);
}

/**
 *  获取视频缩略图
 */
-(void)thumbnailImageRequest {
    //获取视频开始的缩略图
    [self.moviePlayer requestThumbnailImagesAtTimes:@[@0.0,@0.0] timeOption:MPMovieTimeOptionNearestKeyFrame];
    NSLog(@"111");
}


/**
 *  缩略图请求完成,此方法每次截图成功都会调用一次
 *
 *  @param notification 通知对象
 */
-(void)mediaPlayerThumbnailRequestFinished:(NSNotification *)notification {
    NSLog(@"视频截图完成.");
//    UIImage *image=notification.userInfo[MPMoviePlayerThumbnailImageKey];
//    //保存图片到相册(首次调用会请求用户获得访问相册权限)
//    UIImageView *videoImage = [[UIImageView alloc] initWithFrame:self.moviePlayer.view.frame];
//    videoImage.image = image;
//    [self.moviePlayer.view addSubview:videoImage];
    
    
}







-(void)imgbig:(CFUITapGestureRecognizer*)imgTap
{
    [ZLShowBigImage showBigImage:imgTap.tapImgView];
}

-(void)goSaveThePic
{
    
    
    NSMutableArray * savePicArr = [NSMutableArray new];
    NSMutableArray * userDefaultArr = [NSMutableArray new];
    NSDictionary * newdic = [Tools getValueFromNSUserDefaultsByKey:PICIMG_ARR];
    if (newdic[PICIMG_ARR]!= nil) {
        userDefaultArr = newdic[PICIMG_ARR];
    }
    savePicArr = [NSMutableArray arrayWithArray:userDefaultArr];
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    for (int i = 0; i<self.selectPicArry.count; i++) {
        NSData *data2 = UIImageJPEGRepresentation(self.selectPicArry[i], 1.0);
        
        NSLog(@" 1----- documentsDirectory ==== %@",documentsDirectory);
        //    [data1 writeToFile:[homePath stringByAppendingString:@"/Documents/left1.jpg"] atomically:YES];
        NSString * savePicStr = [NSString stringWithFormat:@"Pesronal%d.jpg",i+(int)savePicArr.count+1];
        [data2 writeToFile:[documentsDirectory stringByAppendingPathComponent:savePicStr] atomically:NO];
        
        [savePicArr addObject:savePicStr];
    }
    NSMutableDictionary * savePicDic = [NSMutableDictionary new];
    NSArray * finialArr = [NSArray arrayWithArray:savePicArr];
    
    [savePicDic setValue:finialArr forKey:PICIMG_ARR ];
    [Tools syncNSUserDeafaultsByKey:PICIMG_ARR withValue:(NSDictionary *)savePicDic];
    
}




#pragma mark --------------网络请求
-(void)requestTheNetWith:(NSArray *)myRequestArry andURL:(NSString *)myurl andDic:(NSDictionary *)myDic andRequestSingStr:(NSString *)SingStr;
{
    if (myRequestArry.count>0) {
        [[LJFNetworkingManager shareManager] POST:myurl upLoadImages:myRequestArry parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            NSLog(@"returnData ==== %@",returnData);
            
            if (isOnlineVideo) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
                [[NSFileManager defaultManager] removeItemAtPath:[_videoStrUrl path] error:nil];//上传之后就删除，以免占用手机硬盘空间;
            }else{
                
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        } failure:^(NSError *error) {
            NSLog(@"失败");
            
        } showHUD:self.view];
        
    }else
    {
        [[LJFNetworkingManager shareManager] POST:myurl parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            if ([SingStr isEqualToString:@"video"]) {
                if (code == 1) {
                    statusWithCheck = [returnData[@"status"] intValue];
                    NSString * mediaStr = returnData[@"media"];
                    _myPicUrlArry = [mediaStr componentsSeparatedByString:@","];
                    self.MyPicStrArry = [NSMutableArray arrayWithArray:_myPicUrlArry] ;
                    
                    if (statusWithCheck == 0) {
                        [self.saveBtn setTitle:@"正在审核" forState:UIControlStateNormal];
                        self.saveBtn.userInteractionEnabled = NO;
                    }
                    isreloadIMG = YES;
                    [self.myTableView reloadData];
                }else{
                    
                }
            }else if ([SingStr isEqualToString:@"image"]){
                if (code == 1) {
                    statusWithCheck = [returnData[@"status"] intValue];
                    NSString * mediaStr = returnData[@"media"];
                    _myPicUrlArry = [mediaStr componentsSeparatedByString:@","];
                    self.MyPicStrArry = [NSMutableArray arrayWithArray:_myPicUrlArry] ;
                    
                    if (statusWithCheck == 0) {
                        [self.saveBtn setTitle:@"正在审核" forState:UIControlStateNormal];
                        self.saveBtn.userInteractionEnabled = NO;
                    }
                    isreloadIMG = YES;
                    [self.myTableView reloadData];

                }else{
                    
                }
            }
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        } showHUD:self.view];
        
    }
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
